//
//  HomeViewController.m
//  BookRank
//
//  Created by wststar on 13-10-19.
//  Copyright (c) 2013年 wststar. All rights reserved.
//

#import "HomeViewController.h"
#import "DDMenuController.h"
#import "BaseNavigationController.h"
#import "WeiboModel.h"
#import "WeiboTableView.h"
#import "UIFactory.h"
#import "MenuViewController.h"
#import "AppDelegate.h"
#import "DetailViewController.h"
#import <AudioToolbox/AudioToolbox.h>

@interface HomeViewController ()

@end

@implementation HomeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (self) {
        // Custom initialization
        self.title = NSLocalizedString(@"Home", @"Home");
        //self.tabBarItem = [[UITabBarItem alloc]initWithTitle:self.title image:[UIImage imageNamed:@"tabbar_home.png"] tag:0];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    //自定义菜单按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"注销" style:UIBarButtonItemStylePlain target:self action:@selector(logoutAction:)];
    
    //绑定按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"登录" style:UIBarButtonItemStylePlain target:self action:@selector(loginAction:)];
    
    //添加tableview
    _tableView = [[[WeiboTableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-20-44-49) style:UITableViewStylePlain]autorelease];
    _tableView.eventDelegate = self;
    _tableView.hidden = YES;
    [self.view addSubview:_tableView];
    
    //判断是否认证
    if (self.sinaweibo.isAuthValid) {
        //加载微博列表数据
        [self loadWeiboData];
    }
    
    
}


#pragma mark --显示刷新的微博数目
-(void)showNewWeiboCount:(int) count{
    if (nil ==barView) {
        barView = [[UIFactory createImageView:@"timeline_new_status_background.png"] retain];
        UIImage * image = [barView.image stretchableImageWithLeftCapWidth:5 topCapHeight:5];
        barView.image = image;
        barView.leftCapWidth = 5;
        barView.topCapHeight = 5;
        barView.frame = CGRectMake(5, -40, ScreenWidth-10, 40);
        [self.view addSubview:barView];
        
        UILabel * label = [[[UILabel alloc]initWithFrame:CGRectZero]autorelease];
        label.tag = 2013;
        label.font = [UIFont systemFontOfSize:16.0f];
        label.textColor = [UIColor whiteColor];
        label.backgroundColor = [UIColor clearColor];
        [barView addSubview:label];
    }
    if (count>0) {
        UILabel * label = (UILabel *)[barView viewWithTag:2013];
        label.text = [NSString stringWithFormat:@"%d条新微博",count];
        [label sizeToFit];
        label.origin = CGPointMake((barView.width-label.width)/2, (barView.height-label.height)/2);
    
        //添加动画效果
        [UIView animateWithDuration:0.6 animations:^{
            barView.top = 5;
        } completion:^(BOOL finished) {
            if (finished) {
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDelay:1.0];
                [UIView setAnimationDuration:0.6];
                barView.top = -40;
                [UIView commitAnimations];
            }
        }];
        //播放提示声音
        NSString * filePath = [[NSBundle mainBundle]pathForResource:@"msgcome" ofType:@"wav"];
        NSURL * url = [NSURL fileURLWithPath:filePath];
        SystemSoundID outSystemSoundID ;
        AudioServicesCreateSystemSoundID((CFURLRef)url,&outSystemSoundID);
        AudioServicesPlayAlertSound(outSystemSoundID);
    }
    //隐藏新微博数目
    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [appDelegate.menuViewController showBadge:NO];
}

#pragma mark - load Data
- (void)loadWeiboData {
    //指示器
    [self showLoad:YES];
    //
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObject:@"20" forKey:@"count"];
    [self.sinaweibo requestWithURL:@"statuses/home_timeline.json"
                            params:params
                        httpMethod:@"GET"
                          delegate:self];
}


-(void)refreshWeibo{
    //ui显示下拉状态
    [self.tableView refreshData];
    //取数据
    [self pullDownData];
}

#pragma mark - SinaWeiboRequest delegate
//网络加载失败
- (void)request:(SinaWeiboRequest *)request didFailWithError:(NSError *)error {
    NSLog(@"网络加载失败:%@",error);
}

//网络加载完成
- (void)request:(SinaWeiboRequest *)request didFinishLoadingWithResult:(id)result {
    //NSLog(@"%@",result);
    //关闭指示器
    [self showLoad:NO];
    _tableView.hidden = NO;
    //转换
    NSArray * statues = [result objectForKey:@"statuses"];
    NSMutableArray * weibos = [NSMutableArray arrayWithCapacity:statues.count];
    for (NSDictionary * dic in statues) {
        WeiboModel * weibo = [[WeiboModel alloc]initWithDataDic:dic];
        [weibos addObject:weibo];
        [weibo release];
    }
    NSLog(@"%@",weibos);
    self.tableView.data = weibos;
    self.weibos = weibos;
    
    //保存最上面一条记录的weiboId
    if ([weibos count] > 0) {
        WeiboModel * weibo = [weibos objectAtIndex:0];
        self.topWeiboId = [[weibo weiboId]stringValue];
    }
    
    //刷新
    [self.tableView reloadData];
}

#pragma mark --UITableViewEventDelegate
//上拉
-(void)pullUp:(BaseTableView *)tableView{
    
}
//下拉
-(void)pullDown:(BaseTableView *)tableView{
    [self pullDownData];
}
//选中一个cell
-(void)tableView:(BaseTableView *)tableView
        didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"选中一个cell:%d",indexPath.row);
    WeiboModel * weiboModel = [self.weibos objectAtIndex:indexPath.row];
    DetailViewController * detailViewController = [[[DetailViewController alloc]init]autorelease];
    detailViewController.weiboModel = weiboModel;
    [self.navigationController pushViewController:detailViewController animated:YES];
}

//下拉刷新加载数据
-(void)pullDownData{
    if (self.topWeiboId == nil) {
        NSLog(@"微博id为空");
        return ;
    }
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   @"20",@"count",self.topWeiboId,@"since_id",nil];
    [self.sinaweibo requestWithURL:@"statuses/home_timeline.json"
                            params:params
                        httpMethod:@"GET"
                         block:^(id result) {
                             [self pullDownDataFinish:result];
                         }];
}

-(void)pullDownDataFinish:(id)result{
    NSArray * statues = [result objectForKey:@"statuses"];
    NSMutableArray * weibos = [NSMutableArray arrayWithCapacity:statues.count];
    for (NSDictionary * dic in statues) {
        WeiboModel * weibo = [[WeiboModel alloc]initWithDataDic:dic];
        [weibos addObject:weibo];
        [weibo release];
    }
    
    //更新topWeiboId
    if ([weibos count] > 0) {
        WeiboModel * weibo = [weibos objectAtIndex:0];
        self.topWeiboId = [[weibo weiboId]stringValue];
    }
    
    [weibos addObjectsFromArray:self.weibos];
    self.weibos = weibos;
    self.tableView.data = weibos;
    //刷新
    [self.tableView reloadData];
    //弹回下拉
    [self.tableView doneLoadingTableViewData];
    //显示刷新的数目
    int updateCount = [statues count];
    NSLog(@"下拉刷新数目:%d",updateCount);
    [self showNewWeiboCount:updateCount];
}



#pragma mark - actions
- (void)loginAction:(id *)sender {
    [self.sinaweibo logIn];
}

- (void)logoutAction:(id *)sender {
    [self.sinaweibo logOut];
}


#pragma mark --memory
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
}

- (void)dealloc
{
    
    [super dealloc];
}

@end
